import {Component, OnInit, ViewChild} from '@angular/core';
import {adSystemApiUrl, tuikeSystemUrl} from "../../../../config/api";
import {Headers, RequestOptions} from "@angular/http";
import {HttpService} from "../../../lib/service/http.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ModalDirective} from "ngx-bootstrap";

export class AddkeyWord {
  key = '';
  sort = 0;
}

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss']
})
export class AddComponent implements OnInit {

  addKeyWord = new AddkeyWord();
  type: string;
  message: string;
  isShow = false;
  addStatus = false;
  sortError = false;
  sortTouched = false;
  nameError = false;
  nameTouched = false;
  id;
  edit = false;


  keyCategory;
  @ViewChild('addModal') public addModal: ModalDirective;


  constructor(private router: Router, private httpService: HttpService, private route: ActivatedRoute) {

  }

  ngOnInit() {
    console.log(this.route.snapshot);
    this.id = +this.route.snapshot.queryParams['id'];
    if (this.id) {
      this.edit = true;
      this.getKeywordInfo();
    }
  }

  getKeywordInfo() {
    const url = `${tuikeSystemUrl}/api/v1/admin/task_key/key_info?id=${this.id}`;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        this.addKeyWord.key = res.data.key;
        this.addKeyWord.sort = res.data.sort;
      }
    })
  }

  checkName(e) {
    if (!e.replace(/\s/g, "")) {
      this.nameError = true;
    } else {
      this.nameError = false;
    }
  }

  checkSort(e) {
    if (!/^[1-9]\d*|0$/.test(e + '')) {
      this.sortError = true;
    } else {
      this.sortError = false;
    }
  }


  goBack() {
    this.router.navigate(['tuike/keyword/list']);
  }


  showAddModal() {
    this.addModal.show();
  }

  addKeyword() {
    const url = this.edit ? `${tuikeSystemUrl}/api/v1/admin/task_key/update_key` : `${tuikeSystemUrl}/api/v1/admin/task_key/add_key`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    let body = null;
    if (this.edit) {
      this.addKeyWord['id'] = this.id;
      body = JSON.stringify(this.addKeyWord);
    } else {
      body = JSON.stringify(this.addKeyWord);
    }
    this.addStatus = true;
    this.httpService.httpPostAuth(url, body, options).subscribe(rs => {
      if (rs.code === 200) {
        this.type = 'success';
        this.message = this.edit ? '修改成功' : '添加成功';
        this.isShow = true;
        setTimeout(() => {
          this.addStatus = false;
          this.router.navigate(['tuike/keyword/list']);
        }, 500);
      } else {
        this.addStatus = false;
        this.type = 'error';
        this.message = rs.message;
        this.isShow = true;
      }
    })
  }

}
